/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.alien.admin.modules.deploy.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alien.admin.modules.container.domain.K8sPodMetricStatus;
import com.alien.admin.modules.container.service.K8sDeploymentStatusService;
import com.alien.admin.modules.container.service.K8sPodMetricStatusService;
import com.alien.admin.modules.container.service.dto.K8sDeploymentStatusDto;
import com.alien.admin.modules.container.service.dto.K8sDeploymentStatusQueryCriteria;
import com.alien.admin.modules.deploy.domain.DpUserServer;
import com.alien.admin.modules.deploy.repository.DpUserServerRepository;
import com.alien.admin.modules.deploy.service.DpServerConfigService;
import com.alien.admin.modules.deploy.service.DpServerService;
import com.alien.admin.modules.deploy.service.DpUserServerService;
import com.alien.admin.modules.deploy.service.dto.*;
import com.alien.admin.modules.deploy.service.mapstruct.DpUserServerMapper;
import com.alien.admin.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zengzhifang
* @date 2021-09-09
**/
@Service
@RequiredArgsConstructor
public class DpUserServerServiceImpl implements DpUserServerService {

    private final DpUserServerRepository dpUserServerRepository;
    private final DpUserServerMapper dpUserServerMapper;
    private final DpServerService dpServerService;
    private final K8sDeploymentStatusService k8sDeploymentStatusService;
    private final DpServerConfigService dpServerConfigService;
    private final K8sPodMetricStatusService k8sPodMetricStatusService;

    @Override
    public Map<String,Object> queryAll(DpUserServerQueryCriteria criteria, Pageable pageable){
        String queryName = criteria.getName();

        Long userId = SecurityUtils.getCurrentUserId();
        criteria.setUserId(userId);

        if(StringUtils.isNotEmpty(queryName)) {
            DpServerQueryCriteria dpServerQueryCriteria = new DpServerQueryCriteria();
            dpServerQueryCriteria.setName(queryName);

            List<DpServerDto> serverDtos = dpServerService.queryAll(dpServerQueryCriteria);
            serverDtos.stream().forEach(s -> criteria.getDpServerIds().add(s.getProjectId()));

            if(serverDtos == null || serverDtos.isEmpty()) {
                // 返回空结果
                return PageUtil.toPage(Page.empty());
            }
        }



        // 获取节点状态
        List<K8sDeploymentStatusDto> k8sDeploymentStatusDtoList = k8sDeploymentStatusService.queryAll(new K8sDeploymentStatusQueryCriteria());
        List<K8sPodMetricStatus> k8sPodMetricStatusList = k8sPodMetricStatusService.queryDeploymentMetrics();
        Converter converter = new Converter(criteria.getEnv(), k8sDeploymentStatusDtoList, k8sPodMetricStatusList);

        // 带运行状态，手动分页
        if(criteria.getRunningStatus() == null) {
            Page<DpUserServer> page = dpUserServerRepository.findAll((root, criteriaQuery, criteriaBuilder)
                    -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

            if(StringUtils.isEmpty(criteria.getEnv())) {
                return PageUtil.toPage(page.map(dpUserServerMapper::toDto));
            }
            return PageUtil.toPage(page.map(converter::toDto));
        }

        return pageByStatus(criteria, converter, pageable);
    }

    /***
     * 带运行状态，必须手动分页
     * @return
     */
    Map<String,Object> pageByStatus(DpUserServerQueryCriteria criteria, Converter converter, Pageable pageable) {
        // 获取全部，手动进行分页
        List<DpUserServer> dpUserServerList = dpUserServerRepository.findAll((root, criteriaQuery, criteriaBuilder)
                -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));

        Integer runningStatus = criteria.getRunningStatus();
        List<DpUserServerDto> dpUserServerDtoList = dpUserServerList.stream().map(dpUserServer -> converter.toDto(dpUserServer))
                .filter(dpUserServerDto -> {
                    if(runningStatus != null) {
                        return runningStatus.equals(dpUserServerDto.getRunningStatus());
                    }
                    return true;
                }).collect(Collectors.toList());

        int pageSize = pageable.getPageSize();
        int pageNumber = pageable.getPageNumber();

        int total = dpUserServerDtoList.size();
        int start = pageNumber * pageSize;
        int end = (pageNumber + 1) * pageSize - 1;
        List<DpUserServerDto> content = dpUserServerDtoList.subList(start, end >= total ? total : end);
        Page page = new PageImpl(content, pageable, total);
        return PageUtil.toPage(page);
    }

    @Override
    public List<DpUserServerDto> queryAll(DpUserServerQueryCriteria criteria){
        // 当前用户关联的项目
        Long userId = SecurityUtils.getCurrentUserId();
        criteria.setUserId(userId);

        return dpUserServerMapper.toDto(dpUserServerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DpUserServerDto findById(Long userId) {
        DpUserServer dpUserServer = dpUserServerRepository.findById(userId).orElseGet(DpUserServer::new);
        ValidationUtil.isNull(dpUserServer.getUserId(),"DpUserServer","userId",userId);
        return dpUserServerMapper.toDto(dpUserServer);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DpUserServerDto create(DpUserServer resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setUserId(snowflake.nextId());
        return dpUserServerMapper.toDto(dpUserServerRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DpUserServer resources) {
        DpUserServer dpUserServer = dpUserServerRepository.findById(resources.getUserId()).orElseGet(DpUserServer::new);
        ValidationUtil.isNull( dpUserServer.getUserId(),"DpUserServer","id",resources.getUserId());
        dpUserServer.copy(resources);
        dpUserServerRepository.save(dpUserServer);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long userId : ids) {
            dpUserServerRepository.deleteById(userId);
        }
    }

    @Override
    public void download(List<DpUserServerDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DpUserServerDto dpUserServer : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("创建日期", dpUserServer.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    private class Converter {
        private String env;
        private List<K8sDeploymentStatusDto> k8sDeploymentStatusDtoList;
        private List<K8sPodMetricStatus> k8sPodMetricStatusList;

        public Converter(String env, List<K8sDeploymentStatusDto> k8sDeploymentStatusDtoList, List<K8sPodMetricStatus> k8sPodMetricStatusList) {
            this.env = env;
            this.k8sDeploymentStatusDtoList = k8sDeploymentStatusDtoList;
            this.k8sPodMetricStatusList = k8sPodMetricStatusList;
        }

        K8sPodMetricStatus findK8sPodMetricStatus(DpUserServer dpUserServer, DpServerConfigDto dpServerConfigDto) {
            String projectName = dpUserServer.getDpServer().getName();
            String deploymentName = String.format("%s-deployment", projectName);
            List<K8sPodMetricStatus> k8sPodMetricStatusFilterList = k8sPodMetricStatusList.stream().filter(k8sPodMetricStatus -> {
                Integer k8sId = dpServerConfigDto.getK8sInstanceId();
                String namespace = dpServerConfigDto.getK8sNameSpace();
                return k8sPodMetricStatus.getK8sId().equals(k8sId) &&
                        k8sPodMetricStatus.getNamespace().equals(namespace) &&
                        k8sPodMetricStatus.getDeploymentName().equals(deploymentName);
            }).collect(Collectors.toList());

            if(k8sPodMetricStatusFilterList.isEmpty()) {
                return null;
            }

            return k8sPodMetricStatusFilterList.get(0);
        }

        K8sDeploymentStatusDto findK8sDeploymentStatusDto(DpUserServer dpUserServer, DpServerConfigDto dpServerConfigDto) {
            if(dpServerConfigDto == null) {
                return null;
            }

            // 查询服务的集群状态
            String projectName = dpUserServer.getDpServer().getName();
            String deploymentName = String.format("%s-deployment", projectName.toLowerCase());
            List<K8sDeploymentStatusDto> deploymentStatusDtoList = k8sDeploymentStatusDtoList.stream().filter(k8sDeploymentStatusDto -> {
                Integer k8sId = dpServerConfigDto.getK8sInstanceId();
                String namespace = dpServerConfigDto.getK8sNameSpace();
                return k8sDeploymentStatusDto.getK8sId().equals(k8sId) &&
                        k8sDeploymentStatusDto.getNamespace().equals(namespace) &&
                        k8sDeploymentStatusDto.getDeploymentName().equals(deploymentName);
            }).collect(Collectors.toList());
            if(deploymentStatusDtoList.isEmpty()) {
                return null;
            }

            return deploymentStatusDtoList.get(0);
        }

        private DpUserServerDto toDto(DpUserServer dpUserServer) {
            DpUserServerDto dpUserServerDto = dpUserServerMapper.toDto(dpUserServer);
            DpServerConfigDto dpServerConfigDto = dpServerConfigService.findFirstByProjectIdAndEnv(dpUserServer.getProjectId().intValue(), this.env);

            // 填充集群信息
            if(dpServerConfigDto != null) {
                dpUserServerDto.setK8sNamespace(dpServerConfigDto.getK8sNameSpace());
            } else {
                dpUserServerDto.setK8sNamespace("未知");
            }

            // 获取运行状态runningStatus
            try {
                K8sDeploymentStatusDto k8sDeploymentStatusDto = findK8sDeploymentStatusDto(dpUserServer, dpServerConfigDto);
                if(k8sDeploymentStatusDto == null) {
                    dpUserServerDto.setRunningStatus(DeployConstant.RUNNING_STATUS_UNKNOW);
                } else {
                    dpUserServerDto.setReplicas(k8sDeploymentStatusDto.getReplicas());

                    Integer availableReplicas = k8sDeploymentStatusDto.getAvailableReplicas();
                    if(availableReplicas == null) {
                        dpUserServerDto.setAvailableReplicas(0);
                        dpUserServerDto.setRunningStatus(DeployConstant.RUNNING_STATUS_DEATH );
                    } else {
                        dpUserServerDto.setAvailableReplicas(availableReplicas);
                        dpUserServerDto.setRunningStatus(DeployConstant.RUNNING_STATUS_ALIVE);

                        // 状态为运行，才去查找资源使用，提高效率
                        K8sPodMetricStatus k8sPodMetricStatus = findK8sPodMetricStatus(dpUserServer, dpServerConfigDto);
                        if(k8sPodMetricStatus != null) {
                            Long mem = k8sPodMetricStatus.getMem();
                            // 转换成Mib单位
                            mem = mem / 1024 / 1024;
                            dpUserServerDto.setMem(mem);

                            Double cpu = k8sPodMetricStatus.getCpu();
                            // 转换成m
                            cpu = cpu * 1024;
                            dpUserServerDto.setCpu(cpu);
                        }
                    }
                }
            } catch (Exception e) {
                dpUserServerDto.setRunningStatus(DeployConstant.RUNNING_STATUS_UNKNOW);
            }

            return dpUserServerDto;
        }
    }

    /**
     * 统计某个用户的服务量
     *
     * @param userId
     * @return
     */
    @Override
    public int countServerByUserId(Long userId){
        return dpUserServerRepository.countServerByUserId(userId);
    }
}
